import React, { useState, useEffect, useCallback } from 'react';
import { connect, useDispatch } from 'umi';
import { Modal, Form, Button, Col, Row, Input, List, Tag, message, Divider, Checkbox, Tooltip } from 'antd';
import { ApartmentOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import Ellipsis from '@/components/Ellipsis';
import styles from './UserGroupAddEdit.less';
import UserSelect from '../UserSelect';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const UserGroupAddEdit = (props) => {
  const { drawerType, handleClose, editData } = props;
  const { employeeList: employeeListOfEdit } = editData;
  const defaultCheckedList = [];
  if (employeeListOfEdit && employeeListOfEdit.length > 0) {
    employeeListOfEdit.forEach(({ employeeId, employeeName }) => {
      defaultCheckedList.push({ name: employeeName, value: employeeId, type: 'person' });
    });
  }
  const [checkedList, setCheckedList] = useState(defaultCheckedList);
  const [orgIdSelected, setOrgIdSelected] = useState(0);
  const [employeeOrgList, setEmployeeOrgList] = useState();
  const [pathList, setPathList] = useState([{ orgId: 0, orgName: '上航制造运营管理' }]);
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  useEffect(() => {
    const getEmployeeList = (orgId) => {
      dispatch({
        type: 'userGroupManageModel/getEmployeeAndOrgList',
        payload: {
          parentId: orgIdSelected,
        },
      }).then((res) => {
        const { code, data, message: errMsg } = res;
        const { employeeList, childOrgList } = data;
        if (code === 0 && data) {
          setEmployeeOrgList([...childOrgList, ...employeeList]);
        } else {
          message.error(errMsg);
        }
      });
    };
    getEmployeeList();
  }, [dispatch, orgIdSelected]);


  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields()
      .then((values) => {
        const { userAccount, ...rest } = values;
        const params = { ...rest };
        if (drawerType !== 'add') {
          params.groupId = editData.id;
        }
        const employeeIdList = [];
        const orgIdList = [];
        checkedList.forEach(({ value, type }) => {
          if (type === 'org') {
            orgIdList.push(value);
          } else {
            employeeIdList.push(value);
          }
        });
        params.employeeIdList = employeeIdList;
        params.orgIdList = orgIdList;
        dispatch({
          type: `userGroupManageModel/${drawerType === 'add' ? 'addUserGroup' : 'updateUserGroup'}`,
          payload: params,
        }).then((res) => {
          const { code, message: errMsg } = res;
          if (code === 0) {
            message.success(`${drawerType === 'add' ? '新增' : '编辑'}成功`);
            handleClose(true);
          } else {
            message.error(errMsg);
          }
        });
      });
  };

  const handleUserSelect = useCallback((selectedUser) => {
    const { label, value } = selectedUser;
    setCheckedList((cList) => {
      if (cList.findIndex(item => item.value === value) === -1) {
        return [...cList, { name: label, value, type: 'person' }];
      }
      return cList;
    });
  }, []);

  const handleItemCheckedChange = (e) => {
    const { checked, value, dataName, dataType } = e.target;
    if (checked) {
      setCheckedList([...checkedList, { name: dataName, value, type: dataType }]);
    } else {
      const newList = [...checkedList];
      const valueIndex = newList.findIndex(item => item.value === value);
      if (valueIndex > -1) {
        newList.splice(valueIndex, 1);
        setCheckedList(newList);
      }
    }
  };

  const handleDelTag = ({ value }) => {
    const newList = [...checkedList];
    const valueIndex = newList.findIndex(item => item.value === value);
    if (valueIndex > -1) {
      newList.splice(valueIndex, 1);
      setCheckedList(newList);
    }
  };

  const handleGetChildren = (data) => {
    setOrgIdSelected(data.orgId);
    setPathList([...pathList, data]);
  };

  const handlePathItemClick = (data) => {
    const newPathList = [...pathList];
    newPathList.splice(newPathList.findIndex(item => item.orgId === data.orgId) + 1, 1);
    setPathList(newPathList);
    setOrgIdSelected(data.orgId);
  };

  return (
    <Modal
      title={`${drawerType === 'add' ? '新增' : '修改'}人员组`}
      width={1000}
      visible
      onCancel={handleClose}
      bodyStyle={{ paddingBottom: 40 }}
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleClose} style={{ marginRight: 8 }}> 取消</Button>
          <Button type="primary" onClick={handleSubmit}>{drawerType === 'add' ? '确定' : '保存'}</Button>
        </div>
      )}
    >
      <Row gutter={36}>
        <Col span={14}>
          <Col span={18} offset={6} style={{ padding: 0, marginBottom: 16 }}>
            <UserSelect onSelect={handleUserSelect} placeholder="单击输入用户名以查找用户" style={{ width: '100%' }} />
          </Col>
          <Form {...layout} form={form}>
            <Form.Item
              label="选择员工"
              name="employeeIdList"
              initialValue={editData.employeeIdList}
              style={{ width: '100%' }}
            >
              <div className={styles.tagsWrapper}>
                {checkedList.map(item =>
                  <Tag key={`${item.type}-${item.value}`} closable onClose={() => handleDelTag(item)}>{item.name}</Tag>)}
              </div>
            </Form.Item>
            <Form.Item
              label={(
                <>
                  人员组编码&nbsp;
                  <Tooltip title="人员组编码是唯一的标识">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </>
              )}
              name="groupCode"
              initialValue={editData.groupCode}
              rules={[
                { required: true, message: '请输入人员组编码' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '只允许输入：字母、数字、下划线的字符串组合' },
                { max: 32, message: '字段长度不能超过 32' },
              ]}
            >
              <Input placeholder="请输入人员组编码" />
            </Form.Item>
            <Form.Item
              name="groupName"
              label="人员组名称"
              initialValue={editData.groupName}
              rules={[
                { required: true, message: '请输入人员组名称' },
                { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '只允许输入：字母、数字、下划线、中文字符的字符串组合' },
                { max: 64, message: '字段长度不能超过 64' },
              ]}
            >
              <Input placeholder="请输入人员组名称" />
            </Form.Item>
            <Form.Item name="description" label="描述" initialValue={editData.description}>
              <Input.TextArea placeholder="输入人员组描述（0~150）" rows={8} maxLength={150} />
            </Form.Item>
          </Form>
        </Col>
        <Col span={10} style={{ borderLeft: '1px solid rgba(0,0,0,0.3)' }}>
          <div />
          <div>
            <List
              className={styles.list}
              header={(
                <div>
                  {
                    pathList.map((item, index) => (
                      <span key={item.orgId}>
                        <Button
                          type="link"
                          onClick={() => handlePathItemClick(item)}
                          disabled={pathList.length === index + 1}
                        >
                          {item.orgName}
                        </Button>
                        {pathList.length !== index + 1 && <span style={{ verticalAlign: 'text-bottom' }}>/</span>}
                      </span>
                    ))
                  }
                </div>
              )}
              dataSource={employeeOrgList}
              renderItem={(item) => {
                const { orgId, orgName, employeeId, employeeCode, employeeName, employeeCount } = item;
                const value = orgId || employeeId;
                const name = orgName || employeeName;
                const itemType = orgId ? 'org' : 'person';
                const itemChecked =
                  checkedList.findIndex(listItem => listItem.type === itemType && listItem.value === value) > -1;
                return (
                  <List.Item>
                    <Checkbox
                      checked={itemChecked}
                      onChange={handleItemCheckedChange}
                      value={value}
                      dataName={name}
                      dataType={itemType}
                      style={{ display: 'inline-flex' }}
                    >
                      <Ellipsis
                        length={30}
                        tooltip
                        fullWidthRecognition
                        style={{ display: 'inline', marginRight: 8 }}
                      >
                        {name}
                      </Ellipsis>
                      {employeeId && employeeCode && `(${employeeCode})`}
                      {orgId && employeeCount > 0 && <span>{`(${employeeCount}人)`}</span>}
                    </Checkbox>
                    {
                      orgId && (
                        <div className={styles.rightItemWrapper}>
                          <Divider type="vertical" />
                          <div className={styles.linkWrapper} onClick={!itemChecked ? () => handleGetChildren(item) : () => { }} style={{ cursor: `${itemChecked ? 'not-allowed' : 'pointer'}` }}>
                            <ApartmentOutlined className={styles.rightLink} />
                            <Button type="link" className={styles.rightLink} style={{ cursor: `${itemChecked ? 'not-allowed' : 'pointer'}` }}>下级</Button>
                          </div>
                        </div>
                      )
                    }
                  </List.Item>
                );
              }}
            />
          </div>
        </Col>
      </Row>
    </Modal>
  );
};

export default connect(state => state)(UserGroupAddEdit);
